// 数据模型定义

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use utoipa::ToSchema;

/// 数据源类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub enum DataSourceType {
    HuaweiCloud,
    Database,
    RestAPI,
    OPCUA,
    File,
    MQTT,
}

/// 字段定义
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct FieldDefinition {
    pub name: String,
    pub data_type: DataType,
    pub is_required: bool,
    pub default_value: Option<serde_json::Value>,
    pub description: Option<String>,
}

/// 关系定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relationship {
    pub source: String,
    pub target: String,
    pub relationship_type: String,
    pub properties: HashMap<String, serde_json::Value>,
}

/// 约束定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Constraint {
    pub name: String,
    pub constraint_type: String,
    pub parameters: HashMap<String, serde_json::Value>,
}

/// 数据类型
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub enum DataType {
    String,
    Int32,
    Int64,
    Float,
    Double,
    Boolean,
    DateTime,
    Date,
    Time,
    ByteString,
    Array(Box<DataType>),
    Struct(Vec<FieldDefinition>),
}

/// 实体定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityDefinition {
    pub name: String,
    pub description: Option<String>,
    pub properties: Vec<PropertyDefinition>,
    pub tags: HashMap<String, String>,
}

/// 属性定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropertyDefinition {
    pub name: String,
    pub data_type: DataType,
    pub is_required: bool,
    pub default_value: Option<serde_json::Value>,
    pub description: Option<String>,
}

/// 数据源Schema
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct DataSourceSchema {
    pub entities: Vec<EntityDefinition>,
    pub relationships: Vec<Relationship>,
    pub methods: Vec<MethodDefinition>,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// 方法定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodDefinition {
    pub name: String,
    pub description: Option<String>,
    pub input_parameters: Vec<ParameterDefinition>,
    pub output_parameters: Vec<ParameterDefinition>,
    pub method_type: MethodType,
}

/// 参数定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterDefinition {
    pub name: String,
    pub data_type: DataType,
    pub description: Option<String>,
    pub is_required: bool,
}

/// 方法类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MethodType {
    Read,
    Write,
    Execute,
    Subscribe,
}

/// OPC UA模型
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct OPCUAModel {
    pub model_id: String,
    pub model_name: String,
    pub model_version: String,
    pub description: Option<String>,
    pub namespace_array: Vec<String>,
    pub nodes: Vec<OPCUANode>,
    pub references: Vec<OPCUAReference>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// OPC UA节点
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OPCUANode {
    pub node_id: String,
    pub browse_name: String,
    pub display_name: String,
    pub node_class: OPCUANodeClass,
    pub data_type: Option<DataType>,
    pub value: Option<serde_json::Value>,
    pub description: Option<String>,
}

/// OPC UA节点类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OPCUANodeClass {
    Object,
    Variable,
    Method,
    ObjectType,
    VariableType,
    ReferenceType,
}

/// OPC UA引用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OPCUAReference {
    pub source_node_id: String,
    pub target_node_id: String,
    pub reference_type: String,
    pub is_forward: bool,
}

/// 验证规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationRule {
    pub field_path: String,
    pub rule_type: ValidationType,
    pub parameters: HashMap<String, serde_json::Value>,
    pub message: Option<String>,
}

/// 验证类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationType {
    Required,
    MinLength,
    MaxLength,
    Regex,
    Range,
    Custom,
}

/// 验证结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    pub is_valid: bool,
    pub errors: Vec<ValidationError>,
    pub warnings: Vec<ValidationWarning>,
}

/// 验证错误
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    pub field_path: String,
    pub message: String,
    pub code: String,
    pub value: Option<serde_json::Value>,
}

/// 验证警告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationWarning {
    pub field_path: String,
    pub message: String,
    pub code: String,
    pub value: Option<serde_json::Value>,
}

/// 工作流定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workflow {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub steps: Vec<WorkflowStep>,
    pub triggers: Vec<WorkflowTrigger>,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// 工作流步骤
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowStep {
    pub id: String,
    pub step_type: StepType,
    pub name: String,
    pub description: Option<String>,
    pub parameters: HashMap<String, serde_json::Value>,
    pub next_steps: Vec<String>,
    pub error_handling: ErrorHandling,
}

/// 步骤类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StepType {
    DataExtraction,
    SemanticConversion,
    Validation,
    Notification,
    Custom,
}

/// 工作流触发器
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowTrigger {
    pub trigger_type: TriggerType,
    pub configuration: HashMap<String, serde_json::Value>,
}

/// 触发器类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TriggerType {
    Schedule,
    Event,
    Manual,
    API,
}

/// 错误处理
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorHandling {
    pub strategy: ErrorStrategy,
    pub retry_count: u32,
    pub retry_delay: u64,
}

/// 错误策略
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorStrategy {
    Stop,
    Continue,
    Retry,
    Fallback,
}

/// 工作流执行
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecution {
    pub workflow_id: String,
    pub execution_id: String,
    pub status: ExecutionStatus,
    pub started_at: chrono::DateTime<chrono::Utc>,
    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
    pub current_step: Option<String>,
    pub step_results: HashMap<String, serde_json::Value>,
    pub error: Option<String>,
}

/// 执行状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExecutionStatus {
    Pending,
    Running,
    Completed,
    Failed,
    Cancelled,
}

/// 转换请求
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConversionRequest {
    pub id: String,
    pub source_data_type: String,
    pub target_opcua_type: String,
    pub source_schema: DataSourceSchema,
    pub transformation_rules: TransformationRules,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// 转换结果
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConversionResult {
    pub id: String,
    pub source_schema: DataSourceSchema,
    pub opcua_model: OPCUAModel,
    pub conversion_rules: TransformationRules,
    pub quality_metrics: QualityMetrics,
    pub statistics: ConversionStatistics,
    pub conversion_time: std::time::Duration,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// 转换模式
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConversionMode {
    Automatic,
    Manual,
    SemiAutomatic,
    Learning,
}

/// 转换统计
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConversionStatistics {
    pub total_entities: u32,
    pub converted_entities: u32,
    pub conversion_time: u64,
    pub quality_score: f64,
}

/// 质量指标
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct QualityMetrics {
    pub semantic_completeness: f64,
    pub type_consistency: f64,
    pub performance_efficiency: f64,
    pub scalability: f64,
    pub interoperability: f64,
}

/// 节点ID
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeId {
    pub namespace: u16,
    pub identifier: String,
    pub id_type: IdType,
}

/// ID类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IdType {
    Numeric,
    String,
    Guid,
    ByteString,
}

/// OPC UA对象类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OPCUAObjectType {
    pub node_id: NodeId,
    pub browse_name: String,
    pub display_name: String,
    pub description: Option<String>,
}

/// OPC UA变量
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OPCUAVariable {
    pub node_id: NodeId,
    pub browse_name: String,
    pub display_name: String,
    pub description: Option<String>,
    pub data_type: DataType,
    pub value: Option<serde_json::Value>,
}

/// 引用类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferenceType {
    pub node_id: NodeId,
    pub browse_name: String,
    pub display_name: String,
    pub description: Option<String>,
    pub inverse_name: Option<String>,
}

/// 命名空间数组
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NamespaceArray {
    pub namespaces: Vec<String>,
}

/// 转换规则
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct TransformationRules {
    pub entity_mappings: HashMap<String, String>,
    pub type_mappings: HashMap<String, DataType>,
    pub relationship_rules: Vec<RelationshipRule>,
}

/// 关系规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelationshipRule {
    pub source_pattern: String,
    pub target_pattern: String,
    pub reference_type: String,
    pub condition: Option<String>,
}